<?php

namespace App\Http\Controllers;

use App\Models\Brands;
use App\Models\FrictionEvaluation;
use App\Models\User;
use Illuminate\Http\Request;
use App\Models\CustomerExperienceAssessment;
use App\Models\userAgreeRelation;
use Illuminate\Support\Facades\DB;
use App\Models\brandUserRelation;

class CustomerExperienceAssessmentController extends Controller
{
    protected $items;

    /*
     * upload image
     */
    function assessmentFileUpload(Request $request){
        $image = $request->file('file') ? $request->file('file') : null;
        $openId = $request->input('openId') ? $request->input('openId') : null;
        $subTitle = $request->input('subTitle') ? $request->input('subTitle') : null;
        if(!$image || !$openId || !$subTitle){
            return json_encode(array('code' => '1', 'msg' => 'empty field'));
        }
        $image = $request->file('file');
        //save image in user folder by openid
        $imageName = str_replace(' ', '_', $subTitle) . '_' . time() . '.' . $image->getClientOriginalExtension();
        $input['imagename'] = $imageName;
        $destinationPath = public_path("/images/user/$openId");
        $return = $image->move($destinationPath, $input['imagename']);
        if(!$return){
            return json_encode(array('code' => '2', 'msg' => 'file updoaded failed'));
        }
        return json_encode(array('code' => '0', 'imagePath' => url('/') . "/images/user/$openId/$imageName", 'imageName' => $imageName), JSON_UNESCAPED_SLASHES);
    }

    /*
     * save assessment information
     */
    function assessmentItemSave(Request $request)
    {
        $data = $request->input();
        if (empty($data)) {
            return json_encode(array('code' => '1', 'msg' => 'no request data'));
        }
        //first check if the current item exist, if no, create a new one, if yes, update it
        $currentAssessment = CustomerExperienceAssessment::where('brand_id', $data['brandId'])
                                                            ->where('item', $data['item'])
                                                            ->where('user', $data['openId'])
                                                            ->first();

        if ($currentAssessment) {
            $currentAssessment->description = $data['assessmentItemDescription'] ? $data['assessmentItemDescription'] : ' ';
            $currentAssessment->image = $data['imageName'] ? $data['imageName'] : ' ';
            $currentAssessment->skip = $data['assessmentItemSkip'];
            $result = $currentAssessment->save();
        } else {
            $assessement = new CustomerExperienceAssessment();
            $assessement->brand_id = $data['brandId'];
            $assessement->user = $data['openId'];
            $assessement->description = $data['assessmentItemDescription'] ? $data['assessmentItemDescription'] : ' ';
            $assessement->image = $data['imageName'] ? $data['imageName'] : ' ';
            $assessement->skip = $data['assessmentItemSkip'];
            $assessement->item = $data['item'];
            $result = $assessement->save();
        }
        if (!$result) {
            return json_encode(array('code' => '1', 'msg' => 'save data failed'));
        }

        //after saved the data then check if next step is exist, if no do nothing. If yes, return the information
        $nextItemName = $data['nextStepItem'];
        $nextItem = CustomerExperienceAssessment::where('brand_id', $data['brandId'])
                                                    ->where('item', $nextItemName)
                                                    ->where('user', $data['openId'])
                                                    ->get(['image', 'description', 'skip'])
                                                    ->first();

        //check if this item is the last one, if yes, return all the items information
        $configItems = config('app.items');
        $lastItem = array_pop($configItems);
        $allItems = array();

        if($data['item'] == $lastItem){
            $allItems = CustomerExperienceAssessment::where('brand_id', $data['brandId'])
                ->where('user', $data['openId'])
                ->orderBy('id', 'asc')
                ->get(['item', 'image', 'description', 'skip', 'user', 'id'])
                ->toArray();
            $index = 1;
            foreach ($allItems as &$item){
                $imagePath = "images/user/" . $data['openId'] . '/' . $item['image'];
                if(file_exists($imagePath)){
                    $item['uploadImagePath'] = url('/') . '/' . $imagePath;
                }else{
                    $item['uploadImagePath'] = '';
                }
                $item['userSkip'] = $item['skip'] ? true : false;
                $item['displayFrictionItem'] = $item['skip'] ? 'none' : 'flex';
                $item['index'] = $index;
                $item['hideText'] = true;
                $item['suggestionText'] = '';
                $item['suggestionLike'] = '0';
                $item['disableLike'] = false;
                $item['commentsSaved'] = false;

                $index ++;
            }
        }
        if(!$nextItem){
            return json_encode(array('code' => '0', 'msg' => 'success', 'nextItemExist' => 0,  'nextItem' => array('image' => '', 'description' => '', 'uploadImagePath' => '', 'skip' => false), 'allItems'=> $allItems));
        }else{
            //get image path
            $imagePath = "images/user/" . $data['openId'] . '/' . $nextItem['image'];
            $nextItem = $nextItem->toArray();
            if(file_exists($imagePath)){
                $nextItem['uploadImagePath'] = url('/') . '/' . $imagePath;
            }else{
                $nextItem['uploadImagePath'] = '';
            }
            $nextItem['skip'] = $nextItem['skip'] ? true : false;
            return json_encode(array('code' => '0', 'msg' => 'success', 'nextItemExist' => 1, 'nextItem' => $nextItem, 'allItems'=> $allItems));
        }
    }

    /*
     * get AS items by name
     */
    function assessmentGetItemByName(Request $request){
        $data = $request->input();
        if(!isset($data['openId']) || !isset($data['brandId']) || !isset($data['item'])){
            return json_encode(array('code' => '1', 'msg' => 'empty request field'));
        }
        $assessment = CustomerExperienceAssessment::where('brand_id', $data['brandId'])
                                                        ->where('item', $data['item'])
                                                        ->where('user', $data['openId'])
                                                        ->get(['image', 'description', 'skip'])
                                                        ->first();

        if(!$assessment){
            return json_encode(array('code' => '2', 'msg' => 'no result'));
        }
        $assessment = $assessment->toArray();
        //get image path
        $imagePath = "images/user/" . $data['openId'] . '/' . $assessment['image'];
        if(!file_exists($imagePath)){
            $imagePath = '';
            $assessment['uploadImagePath'] = '';
        }else{
            $assessment['uploadImagePath'] = url('/') . '/' . $imagePath;
        }
        $assessment['skip'] = $assessment['skip'] ? true : false;

        return json_encode($assessment);
    }
    /*
     * getAssessmentInfoByUserBrand
     */
    function getAssessmentInfoByUserBrand(Request $request){
        $data = $request->input();
        if(!isset($data['shareOpenId']) || !isset($data['brandId'])){
            return json_encode(array('code' => '1', 'msg' => 'empty request field'));
        }
        $result = CustomerExperienceAssessment::where('brand_id', $data['brandId'])
                                                ->where('user', $data['shareOpenId'])
                                                ->orderBy('id')
                                                ->get()
                                                ->toArray();
        $frictionAgreeNum = 0;
        $frictionDisagreeNum = 0;
        foreach ($result as $k => &$v){

                $v['userSkip'] = $v['skip'] ? true : false;
                $v['displayFrictionItem'] = $v['skip'] ? 'none' : 'flex';
                $frictions = FrictionEvaluation::select('friction_evaluation.id', 'friction_evaluation.suggesstion', 'friction_evaluation.like', 'friction_evaluation.user', 'users.name')
                                                        ->leftjoin('users', function($leftJoin){
                                                            $leftJoin->on('friction_evaluation.user', '=', 'users.open_id');
                                                        })
                                                        ->where('friction_evaluation.cea_id', '=', $v['id'])
                                                        ->orderBy('friction_evaluation.created_at')
                                                        ->get();
                $v['frictions'] = array();
                if($frictions){
                    $frictionsResult = $frictions->toArray();
                    foreach ($frictionsResult as $value){
                        $othersFrictionAgreeNum = userAgreeRelation::where('friction_id', $value['id'])
                            ->where('agree_user', $value['user'])
                            ->where('agree', 'agree')
                            ->count();
                        $othersFrictionDisagreeNum = userAgreeRelation::where('friction_id', $value['id'])
                            ->where('agree_user', $value['user'])
                            ->where('agree', 'disagree')
                            ->count();
                        if($value['user'] != $data['shareOpenId']) {
                            $v['frictions'][] = array(
                                'id' => $value['id'],
                                'openId' => $value['user'],
                                'name' => $value['name'],
                                'suggestionText' => $value['suggesstion'],
                                'suggestionLike' => $value['like'],
                                'frictionAgreeNum' => $othersFrictionAgreeNum,
                                'frictionDisagreeNum' => $othersFrictionDisagreeNum,
                                'disableLike' => true,
                                'displayFrictionMore' => 'none'
                            );
                        }else{
                            $ownFriction = array(
                                'id' => $value['id'],
                                'openId' => $value['user'],
                                'name' => $value['name'],
                                'suggestionText' => $value['suggesstion'],
                                'suggestionLike' => $value['like'],
                                'frictionAgreeNum' => $othersFrictionAgreeNum,
                                'frictionDisagreeNum' => $othersFrictionDisagreeNum,
                                'disableLike' => true,
                                'displayFrictionMore' => 'none'
                            );
                        }

                    }

                    //order by comment number
                    for( $i = 0; $i < count($v['frictions']); $i++){
                        for($j=$i; $j < count($v['frictions']) - 1; $j++){
                            $tempFriction = $v['frictions'][$j];
                            if ($v['frictions'][$j]['frictionAgreeNum'] < $v['frictions'][$j + 1]['frictionAgreeNum']) {
                                $v['frictions'][$j] = $v['frictions'][$j + 1];
                                $v['frictions'][$j + 1] = $tempFriction;
                            }
                        }
                    }
                    if(isset($ownFriction)){
                        array_unshift($v['frictions'], $ownFriction);
                    }
                    
                }
            $imagePath = "images/user/" . $data['shareOpenId'] . '/' . $v['image'];
            if(!file_exists($imagePath)){
                $imagePath = '';
                $v['uploadImagePath'] = '';
            }else{
                $v['uploadImagePath'] = url('/') . '/' . $imagePath;
            }
            $v['newComment']['hideText'] = true;
            $v['newComment']['suggestionText'] = '';
            $v['newComment']['suggestionLike'] = '0';
            $v['newComment']['disableLike'] = false;
            $v['newComment']['commentsSaved'] = false;
        }

        $user = User::where('open_id', $data['shareOpenId'])->get(['name'])->first()->toArray();
        $brand = Brands::where('id', $data['brandId'])->get(['name'])->first()->toArray();
        $currentOpenid = $data['openId'];
        $finalSave = brandUserRelation::where('brand_id', $data['brandId'])
                                        ->where('user', $currentOpenid)
                                        ->count();
        if(!$finalSave){
            $finalSave = brands::where('id', $data['brandId'])
                ->where('uid', $currentOpenid)
                ->count();
        }
        $finalSave = $finalSave ? true : false;

        return json_encode(array('brandInfo' =>array( 'asItems' => $result, 'shareUserName' => $user['name'], 'sharedBrandName' => $brand['name'], 'finalSave' => $finalSave)));

    }
    //save agree info
    function agreeSave(Request $request){
        $data = $request->input();
        if(!$data['openId'] || !$data['frictionOpenId'] || !$data['frictionId'] || !$data['agree']){
            return json_encode(array('code' => '1', 'msg' => 'empty input field'));
        }
        $resultAgree = userAgreeRelation::where('user', $data['openId'])
                                        ->where('agree_user', $data['frictionOpenId'])
                                        ->where('agree', 'agree')
                                        ->where('friction_id', $data['frictionId'])
                                        ->get()->toArray();

        if(!empty($resultAgree)){
            return json_encode(array('code' => '1', 'msg' => 'already agree'));
        }
        $resultDisagree = userAgreeRelation::where('user', $data['openId'])
                                            ->where('agree_user', $data['frictionOpenId'])
                                            ->where('agree', 'disagree')
                                            ->where('friction_id', $data['frictionId'])
                                            ->get()->toArray();

        if(!empty($resultDisagree)){
            $update = userAgreeRelation::where('user', $data['openId'])->where('agree_user', $data['frictionOpenId'])->update(['agree'=> 'agree']);

            return json_encode(array('code' => '0', 'update' => 'true','msg' => 'data updated'));
        }else {
            $userAgreeRelation = new userAgreeRelation();
            $userAgreeRelation->user =  $data['openId'];
            $userAgreeRelation->agree_user =  $data['frictionOpenId'];
            $userAgreeRelation->agree =  'agree';
            $userAgreeRelation->friction_id = $data['frictionId'];
            $userAgreeRelation->save();
            return json_encode(array('code' => '0', 'update' => 'false','msg' => 'new data saved'));
        }

    }
    //save disagree info
    function disagreeSave(Request $request){
        $data = $request->input();
        if(!$data['openId'] || !$data['frictionOpenId'] || !$data['frictionId'] || !$data['agree']){
            return json_encode(array('code' => '1', 'msg' => 'empty input field'));
        }
        $resultAgree = userAgreeRelation::where('user', $data['openId'])
            ->where('agree_user', $data['frictionOpenId'])
            ->where('agree', 'disagree')
            ->where('friction_id', $data['frictionId'])
            ->get()->toArray();

        if(!empty($resultAgree)){
            return json_encode(array('code' => '1', 'msg' => 'already disagree'));
        }
        $resultDisagree = userAgreeRelation::where('user', $data['openId'])
            ->where('agree_user', $data['frictionOpenId'])
            ->where('agree', 'agree')
            ->where('friction_id', $data['frictionId'])
            ->get()->toArray();

        if(!empty($resultDisagree)){
            $update = userAgreeRelation::where('user', $data['openId'])->where('agree_user', $data['frictionOpenId'])->update(['agree'=> 'disagree']);

            return json_encode(array('code' => '0', 'update' => 'true','msg' => 'data updated'));
        }else {
            $userAgreeRelation = new userAgreeRelation();
            $userAgreeRelation->user =  $data['openId'];
            $userAgreeRelation->agree_user =  $data['frictionOpenId'];
            $userAgreeRelation->agree =  'disagree';
            $userAgreeRelation->friction_id = $data['frictionId'];
            $userAgreeRelation->save();
            return json_encode(array('code' => '0', 'update' => 'false','msg' => 'new data saved'));
        }

    }

    /*
     * getAssessmentInfoByUserBrand
    */
    function getAssessmentInfoByCurrentUserBrand(Request $request){
        $data = $request->input();
        if(!isset($data['openId']) || !isset($data['brandId'])){
            return json_encode(array('code' => '1', 'msg' => 'empty request field'));
        }
        $result = CustomerExperienceAssessment::where('brand_id', $data['brandId'])
            ->where('user', $data['openId'])
            ->orderBy('id')
            ->get()
            ->toArray();
        foreach ($result as $k => &$v){

            $v['userSkip'] = $v['skip'] ? true : false;
            $v['displayFrictionItem'] = $v['skip'] ? 'none' : 'flex';
            $frictions = FrictionEvaluation::select('friction_evaluation.id', 'friction_evaluation.suggesstion', 'friction_evaluation.like', 'friction_evaluation.user', 'users.name')
                ->leftjoin('users', function($leftJoin){
                    $leftJoin->on('friction_evaluation.user', '=', 'users.open_id');
                })
                ->where('friction_evaluation.cea_id', '=', $v['id'])
                ->where('friction_evaluation.user', '=', $data['openId'])
                ->where('friction_evaluation.share_id', '=', ' ')
                ->orderBy('friction_evaluation.created_at')
                ->get();
            $v['frictions'] = array();
            if($frictions){
                $frictionsResult = $frictions->toArray();
                foreach ($frictionsResult as $value){
                    $v['suggestionText'] = $value['suggesstion'];
                    $v['suggestionLike'] = $value['like'] ? $value['like'] : '2';
                    $v['disableLike'] = false;
                }
            }
            $imagePath = "images/user/" . $data['openId'] . '/' . $v['image'];
            if(!file_exists($imagePath)){
                $imagePath = '';
                $v['uploadImagePath'] = '';
            }else{
                $v['uploadImagePath'] = url('/') . '/' . $imagePath;
            }
            $v['hideText'] = false;
            $v['commentsSaved'] = false;
        }

        $user = User::where('open_id', $data['openId'])->get(['name'])->first()->toArray();
        $brand = Brands::where('id', $data['brandId'])->get(['name'])->first()->toArray();

        return json_encode(array('brandInfo' =>array( 'asItems' => $result, 'shareUserName' => $user['name'], 'sharedBrandName' => $brand['name'])));

    }
}
